from flask import render_template, g, redirect, request, jsonify, current_app

from info import constants, db
from info.models import Category, News
from info.moudles.profile import profile_blue
from info.utlis.common import user_login_data
from info.utlis.image_storage import storage
from info.utlis.response_code import RET


@profile_blue.route("/news_list", methods = ["GET", "POST"])
@user_login_data
def news_list():
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    user = g.user
    news_li = []
    current_page = 1
    total_page = 1
    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)
        # 获取当前页数据
        news_li = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []

    for news_item in news_li:
        news_dict_li.append(news_item.to_review_dict())
    data = {"news_list": news_dict_li, "total_page": total_page, "current_page": current_page}
    return render_template("news/user_news_list.html", data = data)







@profile_blue.route("/news_release", methods = ["GET", "POST"])
@user_login_data
def news_release():
    if request.method == "GET":
        categories = []
        try:
            # 获取所有新闻分类
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)

        category_dicts = []
        for category in categories:
            category_dicts.append(category.to_dict())

        category_dicts.pop(0)
        return render_template("news/user_news_release.html", data={"categories":category_dicts})

    title = request.form.get("title")
    category_id = request.form.get("category_id")
    digest = request.form.get("digest")
    index_image = request.files.get("index_image")
    content = request.form.get("content")
    source = "个人发布"
    print(title, category_id, digest, index_image, content, source)
    if not all([title, category_id, digest, index_image, content, source]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
    try:
        index_image = index_image.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
    try:
        key = storage(index_image)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="图片上传失败")


    news = News()
    news.source = source
    news.title = title
    news.content = content
    news.digest = digest
    news.category_id = category_id
    news.user_id = g.user.id
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
    news.status = 1

    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg = "数据保存失败")

    return jsonify(errno = RET.OK, errmsg = "OK")




@profile_blue.route("/user_collection")
@user_login_data
def user_collenction():
    user= g.user
    p = request.args.get("p", "1")
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1
    collections = []
    current_page = 1
    total_page = 1
    try:
        paginate = user.collection_news.paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)
        collections = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_page.logger.error(e)

    collection_dict_li = []
    for news in collections:
        collection_dict_li.append(news.to_basic_dict())
    data = {
        "total_page":total_page,
        "current_page":current_page,
        "collections":collection_dict_li
    }
    return render_template("news/user_collection.html", data = data)





@profile_blue.route("/pass_info", methods=["POST", "GET"])
@user_login_data
def pass_info():
    user = g.user
    if request.method=="GET":
        return render_template("news/user_pass_info.html")

    old_password = request.json.get("old_password")
    new_password = request.json.get("new_password")

    if not all([old_password,new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if not user.check_password(old_password):
        return jsonify(errno=RET.PWDERR, errmsg="密码错误")
    user.password = new_password

    return jsonify(errno=RET.OK, errmsg="OK")


@profile_blue.route("/pic_info", methods=["POST", "GET"])
@user_login_data
def pic_info():
    user = g.user
    if request.method=="GET":
        return render_template("news/user_pic_info.html", data={"user":user.to_dict()})
    try:
        avatar = request.files.get("avatar").read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg="参数错误")
    try:
        key = storage(avatar)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR,errmsg="上传错误")

    user.avatar_url = key
    return jsonify(errno=RET.OK,errmsg="OK", data={"avatar_url":constants.QINIU_DOMIN_PREFIX+key})

@profile_blue.route("/base_info", methods=["POST","GET"])
@user_login_data
def base_info():
    if request.method=="GET":
        user = g.user
        data={
            "user":user.to_dict()
        }
        return render_template("news/user_base_info.html", data=data)
    nick_name = request.json.get("nick_name")
    signature = request.json.get("signature")
    gender = request.json.get("gender")

    if not all([nick_name, signature, gender]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数错误")
    if gender not in ("MAN", "WOMAN"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    user = g.user
    user.signature = signature
    user.nick_name = nick_name
    user.gender = gender

    return jsonify(errno=RET.OK, errmsg="OK")



@profile_blue.route("/info")
@user_login_data
def user_info():
    user = g.user
    if not user:
        return redirect("/")
    data={
        "user":user.to_dict()
    }
    return render_template("news/user.html",data=data)